import React, { cloneElement, createElement, ReactNode } from 'react';
import { isElement, isValidElementType } from 'react-is';

export type LoaderProps = {
  ready?: boolean,
}

export type LoaderComponent = React.ReactElement<LoaderProps> | React.ComponentType<LoaderProps> | undefined | null

export type LoaderFallbackProps = LoaderProps & {
  loader?: LoaderComponent
  children?: ReactNode | ReactNode[],
}

export const LoaderFallback: React.FC<LoaderFallbackProps> = ({ ready = false, loader, children }) => {
  if (!ready && loader != null) {
    if (isElement(loader)) {
      return cloneElement(loader, { ready });
    }
    if (isValidElementType(loader)) {
      return createElement(loader, { ready });
    }
  }
  return <>{children}</>;
};

